package com.tian.job.station;

import com.tian.common.util.StationRedisPreKey;
import com.tian.mapper.ChargeRecordMapper;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import plus.ojbk.influxdb.core.InfluxdbTemplate;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-03-29 19:24
 * {@code @version:} 1.0
 */
@Component
public class MockChargingDataJob {
    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Resource
    private ChargeRecordMapper chargeRecordMapper;
    @Resource
    private InfluxdbTemplate influxDBTemplate;
    @Resource
    private RedissonClient redissonClient;
    private final ConcurrentHashMap<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();

    @Async
    public void mockChargingData(String gunNo) {
        MockChargingData context = new MockChargingData(gunNo, chargeRecordMapper, influxDBTemplate);
        // 每2秒执行一次任务
        ScheduledFuture<?> future = threadPoolTaskScheduler.scheduleWithFixedDelay(
                () -> {
                    RBucket<Boolean> stopFlag = redissonClient.getBucket(StationRedisPreKey.CHARGING_DATA_STOP_FLAG + gunNo);
                    if (stopFlag.get() != null && stopFlag.get()) {
                        // 停止任务
                        cancelExistingTask(gunNo); // 移除任务
                        return;
                    }
                    // 执行数据上报
                    context.run();
                },
                new Date(), 2000L);
        taskMap.put(gunNo, future);
    }

    public static Date add(Date date, int delayMillisSeconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MILLISECOND, delayMillisSeconds);
        return calendar.getTime();
    }

    public void cancelExistingTask(String gunNo) {
        ScheduledFuture<?> existingTask = taskMap.get(gunNo);
        if (existingTask != null) {
            existingTask.cancel(true);
            taskMap.remove(gunNo);
        }
    }
}
